package qs.openxt.libs.plugins;

import android.widget.Toast;

import com.baidu.android.pushservice.PushManager;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import qs.openxt.libs.remoting.Remoting;
import qs.openxt.libs.remoting.Remoting.OnActionListener;
import qs.openxt.libs.util.JSONUtil;
import qs.openxt.libs.util.MessageUtils;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

public class Plugins extends CordovaPlugin{

	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		if ("doRemoting".equals(action)) {
			if(args == null || args.length() == 0){
				Toast.makeText(cordova.getActivity(), "请设置通讯参数", Toast.LENGTH_SHORT).show();
				return false;
			}
			try{
				JSONObject style = null;
				String url = args.optString(0);
				Object data = args.opt(1);
				if(args.length() == 3){
					style = args.optJSONObject(2);
				}
				if(data instanceof JSONObject){
					data = JSONUtil.toJSON((JSONObject)data);
				}

				com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
				param.put("data", data);
				
				Remoting remoting = new Remoting(cordova.getActivity(), new OnActionListener() {
					@Override
					public void onActionFailed(final String errorVal) {
						cordova.getThreadPool().execute(new Runnable() {
							@Override
							public void run() {
								callbackContext.success(errorVal);
							}
						});
					}
					
					@Override
					public void onActionCompleted(final String reVal) {
						cordova.getThreadPool().execute(new Runnable() {
							@Override
							public void run() {
								callbackContext.success(reVal);
							}
						});
					}
				});
				remoting.setServerAddress(url);
				if(style != null){
					remoting.setShowDialogProgress(style.optBoolean("show_progress", true));
					remoting.setHeader(JSONUtil.toJSON(style.optJSONObject("headers")));
				}
				if(style != null && !StringUtil.isNull(style.optString("method")))
					remoting.doRequest(param, style.optString("method"));
				else
					remoting.doRequest(param);
			}catch(Exception e){
			}
			
			return true;
		}else if("bindTags".equals(action)){
			if(args == null || args.length() == 0){
				Toast.makeText(cordova.getActivity(), "请设置tags", Toast.LENGTH_SHORT).show();
				return false;
			}
			
			cordova.getThreadPool().execute(new Runnable() {
				@Override
				public void run() {
					try {
						Utils.setLocalStorage(cordova.getActivity(), Utils.TAGS, args.toString());

						//清理已注册的tags
				 		PushManager.listTags(cordova.getActivity().getApplicationContext());
				 		
						try {
							JSONObject object = new JSONObject();
							object.put("status", "OK");
							callbackContext.success(object);
						} catch (Exception e) {
						}
					} catch (Exception e) {
						try {
							JSONObject object = new JSONObject();
							object.put("status", "ERROR");
							object.put("message", e.getMessage());
							callbackContext.error(object);
						} catch (Exception ex) {
						}
					}
				}
			});
			
			return true;
		}else if("obtainLocalPushMsg".equals(action)){
			if(args == null || args.length() == 0){
				Toast.makeText(cordova.getActivity(), "请设置action", Toast.LENGTH_SHORT).show();
				return false;
			}
			/**		all:获取全部消息
			*		read:已读消息
			*		unread:未读
			*		all_del:获取全部消息,并清空全部消息
			*		read_del:获取已读消息,并清空已读消息
			*		unread_del:获取未读消息,并清空未读消息
			*/
			final String actionName = args.optString(0);
			
			cordova.getThreadPool().execute(new Runnable() {
				@Override
				public void run() {
					try {
						com.alibaba.fastjson.JSONArray array = null;
						if("all".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_ALL);
						}else if("read".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_READ);
						}else if("unread".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_UNREAD);
						}else if("all_del".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_ALL);
							MessageUtils.delMessage(cordova.getActivity(), null);
						}else if("read_del".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_READ);
							List<String> ids = new ArrayList<String>();
							for (int i = 0, j = array.size(); i < j; i++) {
								ids.add(array.getJSONObject(i).getString("uuid"));
							}
							MessageUtils.delMessage(cordova.getActivity(), ids);
						}else if("unread_del".equals(actionName)){
							array = MessageUtils.getMessages(cordova.getActivity(), MessageUtils.TYPE_UNREAD);
							List<String> ids = new ArrayList<String>();
							for (int i = 0, j = array.size(); i < j; i++) {
								ids.add(array.getJSONObject(i).getString("uuid"));
							}
							MessageUtils.delMessage(cordova.getActivity(), ids);
						}
						
						if(array == null)
							array = new com.alibaba.fastjson.JSONArray();
						
						callbackContext.success(JSONUtil.toJSON(array));
					} catch (Exception e) {
						try {
							JSONObject object = new JSONObject();
							object.put("status", "ERROR");
							object.put("message", e.getMessage());
							callbackContext.error(object);
						} catch (Exception ex) {
						}
					}
				}
			});
			
			return true;
		}else if("updateLocalPushMsg".equals(action)){
			if(args == null || args.length() == 0){
				Toast.makeText(cordova.getActivity(), "请设置action", Toast.LENGTH_SHORT).show();
				return false;
			}
			/**	
			*		read:标记为已读
			*		unread:标记为未读
			*		del:清除消息
			*/
			final JSONArray array = args.optJSONArray(0);
			final String actionName = args.optString(1);
			if(array.length() == 0){
				return false;
			}
			
			cordova.getThreadPool().execute(new Runnable() {
				@Override
				public void run() {
					try {
						if("del".equals(actionName)){
							List<String> ids = new ArrayList<String>();
							for (int i = 0, j = array.length(); i < j; i++) {
								ids.add(array.optString(i));
							}
							MessageUtils.delMessage(cordova.getActivity(), ids);
						}else if("read".equals(actionName)){
							List<String> ids = new ArrayList<String>();
							for (int i = 0, j = array.length(); i < j; i++) {
								ids.add(array.optString(i));
							}
							MessageUtils.setMessage(cordova.getActivity(), ids, MessageUtils.TYPE_READ);
						}else if("unread".equals(actionName)){
							List<String> ids = new ArrayList<String>();
							for (int i = 0, j = array.length(); i < j; i++) {
								ids.add(array.optString(i));
							}
							MessageUtils.setMessage(cordova.getActivity(), ids, MessageUtils.TYPE_UNREAD);
						}
						
						try {
							JSONObject object = new JSONObject();
							object.put("status", "OK");
							callbackContext.success(object);
						} catch (Exception ex) {
						}
					} catch (Exception e) {
						try {
							JSONObject object = new JSONObject();
							object.put("status", "ERROR");
							object.put("message", e.getMessage());
							callbackContext.error(object);
						} catch (Exception ex) {
						}
					}
				}
			});
			
			return true;
		}
		return false;
	}
}
